package com.lyw.service;

import com.lyw.dao.UserDao;
import com.lyw.mapper.UserMapper;
import com.lyw.pojo.User;
import com.lyw.util.CodeMsg;
import com.lyw.util.IdWorker;
import com.lyw.util.Result;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    public List<User> findUser() {
        return userDao.findAll();
    }

    public void addUser(User user) {
        user.setId(Long.valueOf(idWorker.nextId()+""));
        user.setSalt("1a2b3c");

        userDao.save(user);
    }

    public void delUser(Long id) {
        userDao.deleteById(id);
    }

    public User findById(Long id) {
        return userDao.findById(id).get();
    }

    public void updUser(User user) {
        userDao.saveAndFlush(user);
    }

    public User login(String username, String password) {
        return userDao.findByUsernameAndPassword(username,password);
    }

    /*public Result zhuce1(User tbUser) {
        int i = UserMapper.zhuce1(tbUser);
        System.out.println("--------------------------------------------------------------");
        System.out.println(i);
        if(i > 0){
            return Result.success(200);
        }else {
            return Result.error(CodeMsg.mistake);
        }

    }*/

    public void sendSms(String mobile, HttpServletRequest request) {


        /*
         * 发送短信验证码 mobile
         */

        // 1、生成六位数的验证码
        Random random = new Random();
        int max = 999999;
        int min = 100000;
        int code = random.nextInt(max);
        if (code < min) {
            code = min + code;
        }
        // 2、存入redis
        HttpSession session = request.getSession();
        session.setAttribute("msd",code);
        // 3.将验证码和手机号发动到rabbitMQ中
        Map<String, String> map = new HashMap();
        map.put("mobile", mobile);
        map.put("code", code + "");
        rabbitTemplate.convertAndSend("msd", map);


    }


}
